<?php

namespace app\services;

use app\payment\PayFactory;
use plugin\admin\app\model\ShareHolding;
use plugin\admin\app\model\User;
use plugin\admin\app\model\UserIdentify;
use plugin\admin\app\model\UserPropertyLog;
use plugin\admin\app\model\UserTeam;
use support\IDCard;

class IdentifyService
{
    public static function auth($data)
    {
        $user = User::find(get_user_id());

        if ($user['is_identify']) {
            throw new \Exception('已实名');
        }

        $data['user_id'] = get_user_id();

        $idcard = new IDCard(getenv('IDCARD_APPCODE'));
//
//        $frontRes = $idcard->ocrFront(base64_encode(file_get_contents($data['front'])));
//        $backRes = $idcard->ocrBack(base64_encode(file_get_contents($data['back'])));
//
//        if ($frontRes['error_code'] == 0) {
//            if ($frontRes['result']['idcardno'] != $data['idcard']) {
//                throw new \Exception('身份证号与证件不匹配');
//            }
//
//            if ($frontRes['result']['name'] != $data['name']) {
//                throw new \Exception('姓名与证件不匹配');
//            }
//        } else {
//            throw new \Exception($frontRes['reason']);
//        }
//
//        if ($backRes['error_code'] == 0) {
//            if ($backRes['result']['end_date'] != null && strtotime($backRes['result']['end_date']) < time()) {
//                throw new \Exception('该证件已过期');
//            }
//        } else {
//            throw new \Exception($backRes['reason']);
//        }

        if (getenv('APP_DEBUG') == 0) {
            $res = $idcard->auth($data['idcard'], $data['name']);

            if ($res['error_code'] == 0) {
                if (!$res['result']['isok']) {
                    throw new \Exception('信息与证件不匹配');
                }
            } else {
                throw new \Exception('查无此人');
            }
        }

        $data['created_time'] = date('Y-m-d H:i:s');
        UserIdentify::insert($data);

        User::where('id', get_user_id())->update(['is_identify' => 1]);

        ShareHoldingService::add(get_user_id());

        $giveSD = ConfigService::get('give_sd');
        if ($giveSD) {
            PropertyService::add(get_user_id(), PayFactory::SD, $giveSD, UserPropertyLog::IDENTIFY);
        }

        if ($user['parent_id'] > 0) {
            UserTeam::where('user_id', $user['parent_id'])->increment('identify_recommend_count');
        }
    }

    public static function isAuth()
    {
        $user = User::find(get_user_id());

        return $user['is_identify'];
    }
}